package com.bkhc.umc.service;

import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.MyBeanUtils;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.UserBean;
import com.bkhc.common.vo.UserRoleVo;
import com.bkhc.common.vo.UserVo;
import com.bkhc.umc.entity.Address;
import com.bkhc.umc.entity.UProductCollection;
import com.bkhc.umc.entity.User;
import com.bkhc.umc.entity.UserRole;
import com.bkhc.umc.repository.*;
import com.bkhc.umc.vo.ApplyInfomation;
import com.bkhc.umc.vo.Customer;
import com.bkhc.umc.vo.UserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class UserSerivce {

    @Autowired
    private UserRepository repository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private AddressRepository addressRepository;
    @Autowired
    private UProductCollectionRepository uProductCollectionRepository;

    public ResultJson<?> queryUser(UserVo userVo, int pageIndex, int pageSize) {

        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex - 1, pageSize, Sort.by(orders));
        Page<User> users = null;
        if (userVo == null) {
            users = repository.findAll(pageRequest);
        } else {
            User user = new User();
            BeanUtils.copyProperties(userVo, user);
            users = repository.findAll(user, pageRequest);
        }
        ResultJson<Page<User>> resultJson = ResultJson.success();
        resultJson.setData(users);
        return resultJson;

    }

    public User queryByUsername(String username) {
        return repository.findByUsername(username);
    }

    public ResultJson<?> addUser(User user) {
        String ss = new BCryptPasswordEncoder().encode("111111");
        user.setPassword(ss);
        if (user == null) {
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        int count = repository.find(user.getUsername(), user.getPhone(), user.getEmail());
        if (count > 0) {
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        user.setStatus("1");
        repository.save(user);
        ResultJson<User> resultJson = ResultJson.success();
        resultJson.setData(user);
        return resultJson;
    }

    public ResultJson<?> updateUser(User user) {
        User userOld = repository.findByUserId(user.getUserId());
        MyBeanUtils.copyProperties(user, userOld);
        repository.save(userOld);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> delete(User user) {
        repository.delete(user);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> getUserRole(String userId, String status) {
        ResultJson<User> resultJson = null;
        User user = repository.findByUserId(userId);
        if (StringUtils.isEmpty(status)) {
            user.setRoles(roleRepository.findAllByUserId(userId));

        } else {
            user.setRoles(roleRepository.findAllByUserIdAndStatus(userId, user.getStatus()));
        }
        resultJson = ResultJson.success();
        resultJson.setData(user);
        return resultJson;
    }

    public ResultJson<?> queryUserRoleDetail(String userId) {
        ResultJson<List<UserRoleVo>> resultJson = null;
        List<UserRoleVo> userRoleVos = repository.findUserRoleByUserId(userId);
        resultJson = ResultJson.success();
        resultJson.setData(userRoleVos);
        return resultJson;
    }

    public ResultJson<?> updateUserRoleDetail(UserRole userRole) {
        Optional<UserRole> optional = userRoleRepository.findById(userRole.getId());
        UserRole oldUserRole = optional.get();
        MyBeanUtils.copyProperties(userRole, oldUserRole);
        userRoleRepository.save(oldUserRole);
        return ResultJson.success();
    }

    public User getUserByUserId(String userId) {
        return repository.findByUserId(userId);
    }

    public List<User> getUserByUsernameFuzzy(String username) {
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(orders));
        Page<User> users = null;
        User user = new User();
        user.setUsername(username);
        users = repository.findAll(user, pageRequest);
        return users.getContent();
    }

    public User getUserByUsername(String username) {
        User user = repository.findByUsername(username);
        return user;
    }

    public ResultJson<?> register(UserInfo userinfo) {
        User user = new User();
        user.setUsername(userinfo.getUsername());
        user.setPassword(userinfo.getPassword());
        user.setPhone(userinfo.getPhone());
        user.setFullName(userinfo.getFullName());

        if (user == null) {
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        int count = repository.find(user.getUsername(), user.getPhone(), user.getEmail());
        if (count > 0) {
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        user.setCreator("system");
        user.setUpdator("system");
        String ss = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(ss);
        user.setStatus("1");
        user.setUserType(userinfo.getUserType());
        repository.save(user);
        //普通用户
        if (user.getUserType() == 0){
            Customer customer = new Customer();
            customer.setMobile(user.getPhone());
            customer.setUsername(user.getUsername());
            customer.setUserId(user.getUserId());
            customer.setInviteCode(userinfo.getInviteCode());
            customer.setCreator(user.getUserId());
            customer.setUpdator(user.getUserId());
            businessRepository.synCustomeToBusinessApp(customer);
        }
        //业务合伙人
        if (user.getUserType() == 1 || user.getUserType() ==3){
            ApplyInfomation infomation = userinfo.getApplyInfomation();
            if(infomation!=null) {
                infomation.setUserId(user.getUserId());
                infomation.setUsername(user.getUsername());
                infomation.setBusinessType(infomation.getBusinessType() == 1 ? 1 : 0);
                businessRepository.applyToBeBusiness(infomation);
            }
        }
        //产品合伙人 TODO
        if (user.getUserType() == 2){

        }
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public User getCurrentUser() {
        UserBean u = CommonUtil.getCrruentUser();
        User user = repository.findByUserId(u.getUserId());
        List<Address> addressList = addressRepository.findByUserId(user.getUserId());
        user.setAddressList(addressList);
        return user;
    }

    public ResultJson<?> updatePassword(UserBean u, String oldPassword, String newPassword) {
        User entity = repository.findByUserId(u.getUserId());
        if(  new BCryptPasswordEncoder().encode(oldPassword).equals(entity.getPassword())){
            entity.setPassword(new BCryptPasswordEncoder().encode(newPassword));
            ResultJson<?> resultJson = ResultJson.success();
            return resultJson;
        }else{
            ResultJson<?> resultJson = ResultJson.failure(ResultCode.ERROR_PASSWORD);
            return resultJson;
        }
    }

    public ResultJson<?> addUPCollection(String productCode) {
        UserBean u = CommonUtil.getCrruentUser();
        UProductCollection uProductCollection =uProductCollectionRepository.findByUserIdAndProductCode(u.getUserId(),productCode);
        if(uProductCollection!=null){
            ResultJson<?> resultJson = ResultJson.success();
            return resultJson;
        }
        UProductCollection uProductCollection1 = new UProductCollection();
        uProductCollection1.setProductCode(productCode);
        uProductCollection1.setUserId(u.getUserId());
        uProductCollectionRepository.save(uProductCollection1);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> deleteUPCollection(String productCode) {
        UserBean u = CommonUtil.getCrruentUser();
        uProductCollectionRepository.deleteByUserIdAndProductCode(u.getUserId(),productCode);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }
}
